package com.duolebo.uteped_sdk.msg;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.duolebo.uteped_sdk.UTEPedEventHandler;
import com.duolebo.uteped_sdk.ota.BleOtaListener;
import com.duolebo.uteped_sdk.ota.OemOtaManager;
import com.duolebo.uteped_sdk.utils.Const;
import com.duolebo.uteped_sdk.utils.PermissionHelper;
import com.duolebo.uteped_sdk.utils.Tools;
import com.yc.nadalsdk.log.LogUtils;

import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class UpgradeMessage extends BaseMessage implements BleOtaListener {
    private final static String PATH = "upgrade";

    private final static String M_startOTA = "startOTA";
    private final static String M_cancelOTA = "cancelOTA";
    private final static String M_googlePlayPlugin = "googlePlayPlugin";

    private final static String GooglePlayPackage = "com.android.vending";


    /**
     * BaseCallback
     *
     * @param methodChannel methodChannel
     * @param eventHandler eventHandler
     */
    public UpgradeMessage(MethodChannel methodChannel, UTEPedEventHandler eventHandler) {
        super(methodChannel, eventHandler);
        OemOtaManager.getInstance(Tools.getApplicationContext());
        OemOtaManager.shareInstance().prepare();
    }

    @Override
    public String getPath() {
        return PATH;
    }

    @Override
    public boolean methodCallConsumed(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        if (!call.hasArgument(Const.KEY_METHOD))
            return false;

        if (super.methodCallConsumed(call, result))
            return true;

        boolean consumed = true;
        String method = call.argument(Const.KEY_METHOD);
        assert method != null;
        switch (method) {
            case M_startOTA:
                String filePath = call.argument(Const.KEY_FILE);
                if (uteBleClient.isConnected()) {
                    OemOtaManager.shareInstance().startOTA(filePath, this);
                    result.success(true);
                }
                else {
                    result.success(false);
                }
                break;

            case M_cancelOTA:
                OemOtaManager.shareInstance().cancelOTA();
                result.success(true);
                break;

            case M_googlePlayPlugin:
                String packageName = call.argument(Const.KEY_TYPE);
                launchAppDetail(packageName);
                result.success(true);
                break;
            default:
                consumed = false;
        }

        return consumed;
    }

    @Override
    public void onOtaStatus(int state) {
        LogUtils.i("ACT--onOtaStatus=" + state);
        switch (state) {
            case OemOtaManager.OTA_STATE_UNKNOWN:
                LogUtils.i("ACT OTA ---未知");
                onOTAError(0, "STATE_UNKNOWN");
                break;
            case OemOtaManager.OTA_STATE_TRANSFERRING:
                LogUtils.i("ACT OTA ---升级中");
                break;
            case OemOtaManager.OTA_STATE_TRANSFERRED:
                LogUtils.i("ACT OTA ---升级完成");
                Map<String, Object> map = new HashMap<>();
                map.put(Const.KEY_PATH, PATH);
                map.put(Const.KEY_METHOD, M_startOTA);
                map.put(Const.KEY_STATUS, state);
                eventHandler.publishEvent(map);
                break;
        }

    }

    @Override
    public void onOTAProgress(int progress) {
        LogUtils.i("ACT--onOTAProgress=" + progress);
        Map<String, Object> map = new HashMap<>();
        map.put(Const.KEY_PATH, PATH);
        map.put(Const.KEY_METHOD, M_startOTA);
        map.put(Const.KEY_STATUS, OemOtaManager.OTA_STATE_TRANSFERRING);
        map.put(Const.KEY_VALUE, progress);
        eventHandler.publishEvent(map);
    }

    @Override
    public void onOTAError(int errCode, String errMsg) {
        LogUtils.i("ACT--onOTAError=" + errCode + ",errMsg=" + errMsg);
        Map<String, Object> map = new HashMap<>();
        map.put(Const.KEY_PATH, PATH);
        map.put(Const.KEY_METHOD, M_startOTA);
        map.put(Const.KEY_STATUS, OemOtaManager.OTA_STATE_UNKNOWN);
        map.put(Const.KEY_ERROR_CODE, errCode);
        map.put(Const.KEY_ERROR_MSG, errMsg);
        eventHandler.publishEvent(map);
    }

    @Override
    public void release() {
        super.release();
        OemOtaManager.shareInstance().release();
    }

    /**
     * 启动到应用商店app详情界面
     *
     * @param appPkg    目标App的包名
     */
    public void launchAppDetail(String appPkg) {
        try {
            if (TextUtils.isEmpty(appPkg)) return;

            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setPackage(GooglePlayPackage);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Tools.getActivity().startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

